"""

Computational Economics
08: Iterators
http://johnstachurski.net/lectures/iterators.html

    Write a program to print out the percentage change in value since the start
    of the year for all of the stocks in this file

    * Change is from Jan 1st until the most recent price available
    * Use the last column (i.e., Adj Close) as the price
    * Stock prices should be downloaded at runtime from Yahoo Finance
    * If you can, print returns in order, from largest to smallest
          o Hint: use the sorted() function

    A hint: if

    line = '2009-06-01,418.73,429.60,418.53,426.56,3322400,426.56\n'

    then line.split(',') returns the elements as a list of strings

"""

from os.path import dirname, join
import urllib
from datetime import date
import pprint

# get list of stocks from file portfolio.txt
fname = 'portfolio.txt'
fpath = join(dirname(__file__), fname)
f = open(fpath)
file_lines = [l.strip() for l in f.readlines() if l.strip() != '']
f.close()

# build dict
stock_dict = {}
for line in file_lines:
    symbol, company = line.split(',')
    stock_dict[symbol.strip()] = company.strip()
#print stock_dict

# add First Am and Core Logic
stock_dict['FAF'] = 'First American Financial Corp'
stock_dict['CLGX'] = 'CoreLogic, Inc'

# request data from yahoo
base_url = 'http://ichart.finance.yahoo.com/table.csv'
today = date.today()
d = '%02i' % (today.month - 1)
e = '%02i' % (today.day)
f = str(today.year)

stock_change = []

for symbol, co in stock_dict.items():
    request_data = {
        's': symbol,            # Ticker symbol for Google
        'a': '00',              # Start month, base zero
        'b': '01',              # Start day
        'c': f,                 # Start year
        'd': d,                 # End month, base zero
        'e': e,                 # End day
        'f': f,                 # End year
        'g': 'd',               # Daily
        'ignore': '.csv'        # Data type
    }

    encoded = urllib.urlencode(request_data)  # Formats the query string
    response = urllib.urlopen(base_url + '?' + encoded)

    response_list = list(response)
    dayn_data = response_list[1].split(',')
    day1_data = response_list[-1].split(',')

    day1_close = float(day1_data[-1].strip())
    dayn_close = float(dayn_data[-1].strip())
    price_change = (dayn_close - day1_close) / day1_close

    stock_change.append(('%s - %s' % (co, symbol), '%.1f%%' % (price_change * 100),
        float(price_change), (day1_data[0], day1_close), (dayn_data[0], dayn_close)))

# sort list
#print stock_change
stock_change.sort(key=lambda tup: tup[2], reverse=True)
pprint.pprint(stock_change)



print '%s: ok' % (__file__)
